package com.first.community.advice;


import com.alibaba.fastjson.JSON;
import com.first.community.dto.ResultDTO;
import com.first.community.exception.CustomizeErrorCode;
import com.first.community.exception.CustomizeExcetpion;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class CustomizeExceptionHandler {

    @ExceptionHandler(Exception.class)
    ModelAndView handler(Throwable ex, Model model, HttpServletResponse response,HttpServletRequest request) {

        String contentType = request.getContentType();

        if("application/json".equals(contentType)){
            ResultDTO resultDTO;

            if (ex instanceof CustomizeExcetpion) {
                resultDTO= ResultDTO.errorOf((CustomizeExcetpion)ex);
            }else{
                resultDTO= ResultDTO.errorOf(CustomizeErrorCode.SYSTEM_ERROR);
            }
            //返回json
            try {
                response.setContentType("application/json");
                response.setStatus(200);
                response.setCharacterEncoding("utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(resultDTO));
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return  null;
        }else{
            //返回错误页面


            if (ex instanceof CustomizeExcetpion) {
                model.addAttribute("message", ex.getMessage());
            }else{
                model.addAttribute("message",CustomizeErrorCode.SYSTEM_ERROR.getMessage());
            }
            return new ModelAndView("error");
        }
    }


}
